﻿using System;
using System.Threading;

namespace SkypeBot.Core
{
    public class SkypeBotLoop
    {
        /// <summary>
        /// Gets a value indicating whether is started.
        /// </summary>
        public bool IsStarted { get; private set; }

        private Thread _workerThread;

        private int _pollInterval = 10; // Every 3 sec

        public void Start()
        {
            ThreadStart st = new ThreadStart(WorkerFunction);
            _workerThread = new Thread(st);

            // set flag to indicate worker thread is active
            IsStarted = true;
            _workerThread.Start();
        }

        public void Stop()
        {
            // flag to tell the worker process to stop
            IsStarted = false;

            // give it a little time to finish any pending work
            // if (this._workerThread != null)
            // this._workerThread.Join(new TimeSpan(0, 0, 30));
        }

        public void Reset()
        {
            Stop();
            Start();
        }

        /// <summary>
        /// Worker function.
        /// </summary>
        private void WorkerFunction()
        {
            if (IsStarted)
            {
                Console.WriteLine("started");
            }

            while (IsStarted)
            {
                DateTime nextRun = DateTime.Now.AddSeconds(_pollInterval);
                while (IsStarted && (DateTime.Now < nextRun))
                    Thread.Sleep(new TimeSpan(0, 0, 1));
                DoWork();
                
            }

            if (!IsStarted)
            {
                Console.WriteLine("stopped");
            }

            Thread.CurrentThread.Abort();
        }

        private void DoWork()
        {
            Console.WriteLine("working");
        }
    }
}


